package org.iabako.server.serviceimpl.support;

import org.apache.log4j.Logger;
import org.iabako.server.conf.AppConf;
import org.iabako.server.dao.support.LogExceptionDAO;
import org.iabako.server.mail.IabakoMailHelper;
import org.iabako.server.mail.IabakoMailSender;
import org.iabako.server.serviceimpl.security.SessionUser;
import org.iabako.server.tools.BundleMessages;
import org.iabako.shared.entity.support.LogException;
import org.iabako.shared.iservice.support.SupportActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by jose on 02/12/14.
 */

@Service("supportService")
public class SupportServiceImpl implements SupportActionService {

    static Logger log = Logger.getLogger(SupportServiceImpl.class.getName());

    @Autowired
    private IabakoMailSender iabakoMailSender;
    @Autowired
    private AppConf appConf;
    @Autowired
    BundleMessages messages;
    @Autowired
    LogExceptionDAO logExceptionDAO;
    @Autowired
    SessionUser sessionUser;

    public void askQuestion(String emailFrom, String questionBody) {

        IabakoMailHelper iabakoMailHelper = new IabakoMailHelper(emailFrom, null, appConf.getClientServiceEmail(), messages.getLabel("question_mail_subject"), questionBody);
        iabakoMailSender.sendMail(iabakoMailHelper);

        log.info("A QUESTION Email have been sent from " + emailFrom);
    }

    public void reportBug(String from, String body) {

        IabakoMailHelper iabakoMailHelper = new IabakoMailHelper(from, null, appConf.getClientServiceEmail(), messages.getLabel("bug_mail_subject"), body);
        iabakoMailSender.sendMail(iabakoMailHelper);

        log.info("A BUG Email have been sent from " + from);
    }

    public void requestDeleteInformation(String from, String body) {
        IabakoMailHelper iabakoMailHelper = new IabakoMailHelper(from, null, appConf.getClientServiceEmail(), messages.getLabel("question_mail_subject"), body);
        iabakoMailSender.sendMail(iabakoMailHelper);

        log.info("A Request to DELETE all information have been sent from " + from);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void logException(String exception) {

        LogException logException = new LogException();
        logException.setUserEmail(sessionUser.getUser() != null ? sessionUser.getUser().getEmail() : null);
        logException.setException(exception);

        logExceptionDAO.persist(logException);
    }
}
